﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MvcSample.Data;
using MvcSample.Data.Core;
using MvcSample.Models;

namespace MvcSample.Services
{
    public class StudentService
        : IStudentService
    {
        private readonly ApplicationContext _ctx;
        public StudentService(ApplicationContext ctx)
        {
            _ctx = ctx;
        }

        public async Task AddAsync(Student stu)
        {
            await _ctx.Student.AddAsync(stu);
            await _ctx.SaveChangesAsync();
        }

        public async Task<List<StudentOutputDto>> GetAllAsync()
        {
            var rt = await _ctx.Student.AsNoTracking().ToListAsync();
            var dtos = rt.Select(s => new StudentOutputDto(s)).ToList();
            return dtos;
        }

        public async Task<StudentOutputDto> GetByIdAsync(int id)
        {
            var stu = await _ctx.Student.SingleOrDefaultAsync(s => s.Id == id);
            return new StudentOutputDto(stu);
        }

        public async Task<int> GetCountAsync()
        {
            return await _ctx.Student.CountAsync();
        }
    }
}
